package com.mca.framework.completableFuture;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @Author: zhoupeng
 * @createTime: 2025年07月07日 22:04:04
 * @version: 1.0
 * @Description:
 * @copyright:
 */
public class RunAfterBothDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int f1 = new Random().nextInt(100);
            System.out.println("f1 value：" + f1);
            return f1;
        },executorService);

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int f2 = new Random().nextInt(100);
            System.out.println("f2 value：" + f2);
            return f2;
        },executorService);
        //runAfterBothAsync 表示  future1与future2 都执行完了才执行里面代码  CompletableFuture.allOf
        future1.runAfterBothAsync(future2,()->{
            try {
                //总是获取到future2的结果  虽然future1先执行完了，但是得等future2 返回的结果
                //业务场景： 一个线程执行完，等待另一个线程执行的后的结果
                System.out.println("两个任务都已执行完"+future2.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            executorService.shutdown();
        },executorService);
    }
}
